Post

Replies

Boosts

Views

Activity

SwiftUI: @StateObject never deinitialized
I am using @StateObject for creating a view model for my view. The problem is that the ViewModel is still in memory after closing the view and deinit is never called. If I open and close the view 10 times, the debug memory graph shows me 10 ViewModels. I created a very simple example to replicate the problem: import SwiftUI struct MySwiftUIView: View { @Environment(\.presentationMode) private var presentation @StateObject var viewModel = MyViewModel() var body: some View { Text("Hallo World.") .navigationBarBackButtonHidden(true) .navigationBarItems(leading: Button( action: { presentation.wrappedValue.dismiss() }, label: { Text("back") })) } } class MyViewModel: ObservableObject { init() { print(">> init") } deinit { print("[x] deinit") } } ">> init" is printed every time when I am opening the view, but "[x] deinit" is never printed. This is how I am opening the view: import SwiftUI struct ContentView: View { var body: some View { NavigationView { VStack{ NavigationLink(destination: MySwiftUIView()){Text("NavigationLink")} } }.navigationViewStyle(StackNavigationViewStyle()) } } Does anybody have an idea why the ViewModel never gets destroyed? I created a demo project in Xcode which can be found here: https://file.io/QQnHDvRNaGPP edit: It works with the newest iOS15 Beta, but not with iOS14.5 or lower.
3
2
4.2k
Aug ’21